package com.adamall.controller;

import com.adamall.dao.CartMapper;
import com.adamall.dao.OrdersMapper;
import com.adamall.dao.ShopMapper;
import com.adamall.module.Cart;
import com.adamall.module.CartExample;
import com.adamall.module.OrdersExample;
import com.adamall.module.ShopExample;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")

public class Cart_Controller {

    @Autowired
    CartMapper cartMapper;
    CartExample cartExample;
    CartExample.Criteria criteria;

    @Autowired
    ShopMapper shopMapper;

    @Autowired
    OrdersMapper ordersMapper;
    OrdersExample ordersExample;
    OrdersExample.Criteria orders_criteria;


    @PostMapping("cart")
    public ResponseEntity<String> addCart(@RequestBody String products) {
        List<Map<String, Integer>> mapList = getKey(products);

        for (int i = 0; i < mapList.size(); i++) {
            Cart cart = new Cart();
            Map<String, Integer> map = mapList.get(i);
            cart.setProductsId(map.get("id"));
            cart.setProductsNumber(map.get("number"));
            cart.setShop(shopMapper.selectByPrimaryKey(map.get("id")).getId());
            cartMapper.insert(cart);
            System.out.println();
        }

        return ResponseEntity.ok().header("Custom-Header", "Successful POST request").body("添加成功");
    }

    //下订单
    @PostMapping("orders")
    public ResponseEntity<Object> PlaceAnOrder(@RequestBody String products) {
        List<Map<String, Integer>> mapList = getKey(products);
        
        return null;
    }

    public List<Map<String, Integer>> getKey(String products) {
        List<Map<String, Integer>> mapList = new ArrayList<>();
        JSONObject jsonObj = JSON.parseObject(products);
        for (String key : jsonObj.keySet()) {
            if (key.equals("products")) {
                JSONArray val = jsonObj.getJSONArray(key);
                for (int i = 0; i < val.size(); i++) {
                    Map<String, Integer> map = (Map<String, Integer>) val.get(i);
                    mapList.add(map);
                }
            }
        }
        return mapList;
    }

}
